<!-- subpkg_consult/room/index.vue -->
<script lang="ts" setup>
import { nextTick, ref } from "vue"
import { baseUrl } from "@/utils/http"
import { useUserStore } from "@/stores/user"
import { uploadImageApi } from "@/apis/upload"
import { getOrderDetailApi } from "@/apis/consult"
import type { OrderDetail } from "@/types/consult"
import type { MsgData, MsgItem } from "@/types/room"
import RoomStatus from "./components/room-status.vue"
import PatientInfo from "./components/patient-info.vue"
import NotifyInfo from "./components/notify-info.vue"
import MessageInfo from "./components/message-info.vue"
import PrescriptionInfo from "./components/prescription-info.vue"
import RateInfo from "./components/rate-info.vue"
// #ifdef APP || H5
import { io, type Socket } from "socket.io-client"
// #endif
// src="https://cdn.socket.io/4.4.1/socket.io.min.js"
//orderId=7092145858519040&payResult=true&type=2
const pageParams = defineProps<{
  orderId: string
  payResult: "true" | "false"
  type: string
}>()
// 支付宝放弃支付 / 支付失败
if (pageParams.payResult === "false") {
  // 跳转个人中心页
  uni.reLaunch({ url: "/pages/my/index" })
}
const userStore = useUserStore()

// #ifdef APP || H5
const socket: Socket = io(baseUrl, {
  auth: { token: `Bearer ${userStore.getToken()}` },
  query: { orderId: pageParams.orderId },
  transports: ["websocket", "polling"],
  timeout: 2000,
})

socket.on("connect", () => {
  // 建立连接成功
  console.log("连接建立成功")
})

socket.on("error", () => {
  // 错误异常消息
  console.log("出现错误")
})

socket.on("disconnect", () => {
  // 已经断开连接
  console.log("断开连接")
})
// #endif

// 订单详情
const orderDetail = ref<OrderDetail>()

// 获取订单详情
const getOrderDetail = async () => {
  const res = await getOrderDetailApi(pageParams.orderId)
  orderDetail.value = res
  // console.log(res)
}
getOrderDetail()

// 消息列表
const messageList = ref<MsgItem[]>([])
// #ifdef APP || H5

// 获取历史消息
socket.on("chatMsgList", async (res: MsgData) => {
  // 没有返回数据
  if (res.code != 10000) return
  // 提取列表数据
  if (res.data?.length) {
    // messageList.value.push(...res.data[0].items!)
    // 消息分段 后端对消息做了分段处理
    res.data.forEach((item) => {
      // 主动插入普通消息
      messageList.value.push(
        {
          createTime: item.createTime,
          msgType: 31,
          msg: {
            content: item.createTime,
          },
        },
        ...item.items! // 正常消息列表
      )
    })
  }
  // console.log("历史消息", messageList.value)
  // 等待前面的数据和视图更新完成，再往后执行任务
  await nextTick()
  // 设置为最后一项的id, 让滚动条滚到最后面
  activeIndexText.value = `item-${messageList.value.length - 1}`
})

// 自动接收消息
socket.on("statusChange", () => {
  getOrderDetail()
})

// 接收消息
socket.on("receiveChatMsg", async (res: MsgItem) => {
  // console.log("收到一条新消息", res.msg?.content)
  // 修改消息为已读
  socket.emit("updateMsgStatus", res.id)
  // 追加到消息列表
  messageList.value.push(res)
  // 等待前面的数据和视图更新完成，再往后执行任务
  await nextTick()
  // 设置为最后一项的id, 让滚动条滚到最后面
  activeIndexText.value = `item-${messageList.value.length - 1}`
})
// #endif
// 跳转首页 reLaunch 或者 switchTab
const gotoIndexPage = () => {
  uni.switchTab({ url: "/pages/index/index" })
}

// 输入框消息
const textMessage = ref("")

// 发送消息
const sendMessage = () => {
  const message = textMessage.value.trim()
  if (message === "") {
    return uni.showToast({ title: "请输入内容", icon: "none" })
  }
  // 清空表单
  textMessage.value = ""
  // #ifdef APP || H5
  // 通过 WebSocket 发送消息（注意：这里不是 POST 请求）
  socket.emit("sendChatMsg", {
    from: userStore.getUserId(),
    to: orderDetail.value?.docInfo?.id, // 患者id 用户id
    msgType: 1, // 文字类型
    msg: { content: message }, // 消息内容
  } as MsgItem)
  // #endif
}

// 发送图片
const sendImage = async () => {
  // 1. 选择图片
  const res = await uni.chooseImage({ count: 1 })
  // 如果选择了图片
  if (res.tempFilePaths[0]) {
    // 2. 上传图片
    const imageInfo = await uploadImageApi(res.tempFilePaths[0])

    // 3. 发送图片消息
    // #ifdef APP || H5
    socket.emit("sendChatMsg", {
      from: userStore.getUserId(), // 患者id 用户id
      to: orderDetail.value?.docInfo?.id, // 医生id
      msgType: 4, // 图片类型
      msg: { picture: imageInfo }, // 消息内容
    } as MsgItem)
    // #endif
  }
}

// 设置滚动位置，值应为某子元素id（id不能以数字开头）
const activeIndexText = ref("")
</script>

<template>
  <view class="room-page">
    <RoomStatus
      v-if="orderDetail?.id"
      :status-value="orderDetail?.statusValue"
      :status="orderDetail?.status"
      :countdown="orderDetail?.countdown"
    />
    <scroll-view
      refresher-enabled
      refresher-background="#f2f2f2"
      scroll-y
      style="flex: 1; overflow: hidden"
      :scroll-into-view="activeIndexText"
    >
      <view class="message-container">
        <!-- 此处将来填充更多代码... -->
        <!-- template 的 id 无法正常使用，换成 view-->
        <view
          v-for="(item, index) in messageList"
          :key="item.id"
          :id="`item-${index}`"
        >
          <!-- 
            21	患者信息
            22	处方信息
            23	未提交评价
            24	已提交评价
            31	普通通知
            32	温馨提示
            33	取消订单
            4	  图片消息
            1	  文字消息
          -->
          <!-- 21 患者消息 -->
          <PatientInfo
            v-if="item.msgType === 21"
            :info="item.msg?.consultRecord!"
          />
          <!-- 22 处方信息 -->
          <PrescriptionInfo
            v-else-if="item.msgType === 22"
            :info="item.msg?.prescription!"
          />
          <!-- 23	未提交评价 24	已提交评价 -->
          <RateInfo
            v-else-if="[23,24].includes(item.msgType!)"
            :type="item.msgType!"
            :evaluate-doc="item.msg?.evaluateDoc"
            :doc-id="orderDetail?.docInfo?.id!"
            :order-id="orderDetail?.id!"
          />
          <!-- 31 普通通知 32 温馨提示 33 取消订单 -->
          <NotifyInfo
            v-else-if="[31,32,33].includes(item.msgType!)"
            :type="item.msgType"
          >
            {{ item.msg?.content }}
          </NotifyInfo>
          <!-- 4 图片消息 1 文字消息 -->
          <MessageInfo
            v-else-if="[4,1].includes(item.msgType!)"
            :type="item.msgType!"
            :info="item"
          ></MessageInfo>
        </view>
      </view>
    </scroll-view>

    <!-- 发送消息 -->
    <view class="message-bar">
      <!-- 
        订单状态：1待支付2待接诊3咨询中4已完成5已取消/药品订单10待支付11待发货12待收货13已完成14已取消
        >3 隐藏输入框 
        非咨询状态，都禁用输入框
        -->
      <template v-if="orderDetail?.status <= 3">
        <uni-easyinput
          :disabled="orderDetail?.status !== 3"
          :clearable="false"
          :input-border="false"
          placeholder-style="font-size: 32rpx; color: #c3c3c5;"
          placeholder="问医生"
          v-model="textMessage"
          @confirm="sendMessage"
        />
        <view class="image-button" @click="sendImage">
          <uni-icons size="40" color="#979797" type="image"></uni-icons>
        </view>
      </template>
      <button v-else class="uni-button" @click="gotoIndexPage">
        咨询其它医生
      </button>
    </view>
  </view>
</template>

<style lang="scss">
@import "./index.scss";
</style>
